package com.sgy.netty.server;

import com.sgy.netty.init.MyChannelInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class NettyServer implements ApplicationRunner {
    private static final Logger log = LoggerFactory.getLogger(NettyServer.class);

    @Value("${websocket.port}")
    private String port;

    public void start(ApplicationArguments args) throws InterruptedException {
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup work = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.option(ChannelOption.SO_BACKLOG,1024);
            bootstrap.group(boss,work)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(Integer.valueOf(port))
                    .childHandler(new MyChannelInitializer());
            //服务器异步创建绑定
            ChannelFuture future = bootstrap.bind().sync();
            log.info("Web Server start!!!正在监听："+future.channel().localAddress());
            //关闭服务器通道
            future.channel().closeFuture().sync();
        } finally {
            //退出，释放线程池资源
            boss.shutdownGracefully();
            work.shutdownGracefully();
        }
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.debug("-------------->"+"项目启动，now="+new Date());
        log.debug("获取到的参数： "+args.getOptionNames());
        log.debug("获取到的参数： "+args.getNonOptionArgs());
        log.debug("获取到的参数： "+args.getSourceArgs());
        start(args);
    }
}
